package org.javaforever.oville;

public class StringUtil {
	public static boolean isBlank(Object o){
		if (o==null || "".equals(o) || "".equals(o.toString().trim())) return true;
		else return false;
	}

	public static String binDigToHex(String bin) throws ValidateException{
		switch (bin) {
        case "0000":
            return "0";
        case "0001":
            return "1";
        case "0010":
            return "2";
        case "0011":
            return "3";
        case "0100":
            return "4";
        case "0101":
            return "5";
        case "0110":
            return "6";
        case "0111":
            return "7";
        case "1000":
            return "8";
        case "1001":
            return "9";
        case "1010":
            return "a";
        case "1011":
            return "b";
        case "1100":
            return "c";
        case "1101":
            return "d";
        case "1110":
            return "e";
        case "1111":
            return "f";
        default:
        	System.out.println(bin);
        	throw new ValidateException("不是合法４为二进制字符串！");
        }
	}
	
	public static String binDigToQuad(String bin) throws ValidateException{
		switch (bin) {
        case "00":
            return "0";
        case "01":
            return "1";
        case "10":
            return "Q";
        case "11":
            return "P";
        default:
        	System.out.println(bin);
        	throw new ValidateException("不是合法４为二进制字符串！");
        }
	}
	
	public static NarrowWord strToNarrowWord(String input,String varName) throws ValidateException{
		if (input.startsWith("0x")&&input.length()==10) {
			String pureInput = input.substring(2,input.length());
			NarrowWord nw = new NarrowWord();
			nw.setVarName(varName);
			byte [] bytes = StringToHex.hexStringToByteArray(pureInput);
			nw.setNarrowWord(bytes);
			return nw;			
		}else if (input.startsWith("0b")&&input.length()== 34) {
			String pureInput = input.substring(2,input.length());
			NarrowWord nw = NarrowWord.fromBinStr(pureInput);
			nw.setVarName(varName);
			return nw;			
		}
		throw new ValidateException("Wrong narrowWord string.");		
	}
	
	public static Word strToWord(String input,String varName) throws ValidateException{
		System.out.println("JerryDebug:"+input +":"+input.length());
		if (input.startsWith("0q")&&input.length()==34) {
			String pureInput = input.substring(2,input.length());			
			Word w = Word.fromQuadStr(pureInput);
			w.setVarName(varName);
			return w;			
		}
		throw new ValidateException("Wrong quad string for word.");
	}
	
	public static NarrowWords strToNarrowWords(String input,String varName) {
		if (input.startsWith("0x")) input = input.substring(2,input.length());
		return StringToHex.hexStringToNarrowWords(input,varName);
	}
}
